package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加好友
     * @param userId
     * @param friendId
     */
    @Override
    public void makeFriends(Long userId, Long friendId) {
        long millis = System.currentTimeMillis();
        addFriend(userId, friendId, millis);
        addFriend(friendId, userId, millis);
    }

    /**
     * 分页获取好友列表
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<Friend> getList(Long page, Long pageSize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);
        long skip = (page - 1) * pageSize;
        List<Friend> friends = new ArrayList<>();
        if(count > skip) {
            query.skip(skip).limit(pageSize.intValue());
            friends = mongoTemplate.find(query, Friend.class);
        }
        return new PageResult<>(page, pageSize, count, friends);
    }

    /**
     * 获取所有好友
     * @param userId
     * @return
     */
    @Override
    public List<Friend> getAllFriend(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.find(query, Friend.class);
    }


    private void addFriend(Long userId, Long friendId, Long millis) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("friendId").is(friendId));
        Friend existFriend = mongoTemplate.findOne(query, Friend.class);
        if (null == existFriend) {
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(millis);
            mongoTemplate.insert(friend);
        }
    }
}
